import React, { useEffect } from "react"
import { Image, View } from "@tarojs/components"
import Taro, { usePullDownRefresh, useReachBottom } from "@tarojs/taro"
import { useSetState } from "@/utils/hooks"
import GpContainer from "@/components/GpContainer"
import GpActionSheet from "@/components/GpActionSheet"
import styles from "./index.module.scss"
import { getMyConcern, switchConcern, topConcern, untopConcern } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import clsx from "clsx"
import { navigation } from "@/utils/router"
import { pageMapperCommunity } from "@/constants/pageMap"
import GpEmpty from "@/components/GpEmpty"

type IState = {
  list: IApiRelative.IGetMyConcern.IGetMyConcernItem[]
  openAction: boolean
  hasMore: boolean
  current: number
  currentTarget: INullable<IApiRelative.IGetMyConcern.IGetMyConcernItem>
  actions: any[]
}
/**
 * @page 我的关注
 */
const MyConcern: React.FC = function () {
  const [state, setState, stateRef] = useSetState<IState>(
    {
      list: [],
      openAction: false,
      hasMore: true,
      current: 1,
      currentTarget: null,
      actions: [
        {
          name: "置顶关注",
          value: "top"
        },
        {
          name: "取消关注",
          value: "cancel",
          danger: true
        }
      ]
    },
    true
  )
  useEffect(() => {
    fetchConcerns()
  }, [])
  usePullDownRefresh(() => {
    setState({ hasMore: true, current: 1, currentTarget: null })
    fetchConcerns()
    Taro.stopPullDownRefresh()
  })
  useReachBottom(() => {
    if (state.hasMore) {
      setState({ current: stateRef.current!.current + 1, currentTarget: null })
      fetchConcerns()
    }
  })
  function handleConcern(currentTarget: IApiRelative.IGetMyConcern.IGetMyConcernItem) {
    const actions = state.actions.concat()
    if (currentTarget.isTop) {
      actions[0].name = "取消置顶"
    } else {
      actions[0].name = "置顶关注"
    }
    setState({ openAction: true, currentTarget, actions })
  }
  function closeAction() {
    setState({ openAction: false })
  }
  function handleActionSelect({ value }) {
    if (!stateRef.current!.currentTarget) return
    const target = stateRef.current!.currentTarget
    if (value === "top") {
      /**
       * 前台交互：如果置顶操作，则将目标元素置顶到最前，
       * 如果是取消置顶，则将目标元素放置在最后一个置顶元素之后
       */
      const isTop = target.isTop
      const action = isTop
        ? untopConcern({ followingMiniVisitorId: target.miniVisitorId })
        : topConcern({ followingMiniVisitorId: target.miniVisitorId })
      action.then(res => {
        if (requestIsFullfilled(res)) {
          Taro.showToast({ title: "操作成功", icon: "none" })
          const _list = stateRef.current!.list.concat()
          const index = _list.findIndex(
            l => l.followingMiniVisitorId === target.followingMiniVisitorId
          )
          if (~index) {
            _list[index].isTop = !isTop
            const [finder] = _list.splice(index, 1)
            if (isTop) {
              _list.unshift(finder)
            } else {
              let lastConcernIndex = -1
              for (let i = _list.length - 1; i >= 0; i--) {
                if (_list[i].isTop) {
                  lastConcernIndex = i
                  break
                }
              }
              if (~lastConcernIndex) {
                _list.splice(lastConcernIndex + 1, 0, finder)
              } else {
                _list.unshift(finder)
              }
            }
            setState({ list: _list, currentTarget: null })
          }
        }
      })
    } else if (value === "cancel") {
      Taro.showModal({
        content: "确认不再关注该账号?",
        success(result) {
          if (result.confirm) {
            switchConcern({ followingMiniVisitorId: target.followingMiniVisitorId }).then(res => {
              if (requestIsFullfilled(res)) {
                const _list = stateRef.current!.list.concat()
                const index = _list.findIndex(
                  l => l.followingMiniVisitorId === target.followingMiniVisitorId
                )
                if (~index) {
                  _list.splice(index, 1)
                  setState({
                    list: _list,
                    currentTarget: null
                  })
                }
              }
            })
          }
        }
      })
    }
  }
  function fetchConcerns() {
    Taro.showLoading({ title: "加载中..." })
    getMyConcern({
      pagination: {
        current: stateRef.current!.current,
        pageSize: 10
      },
      sort: {
        predicate: "",
        reverse: false
      },
      search: {}
    })
      .then(res => {
        Taro.hideLoading()
        if (requestIsFullfilled(res)) {
          const { list, pagination } = res.data.data
          setState({
            list: pagination.current === 1 ? list : [...stateRef.current!.list, ...list],
            hasMore: pagination.current < pagination.pageCount
          })
        }
      })
      .catch(() => {
        Taro.hideLoading()
      })
  }
  function renderEmpty() {
    return (
      <GpEmpty
        imageProps={{
          src: "https://static.91goodschool.com/UpFiles/public/yikao/image/aixin.png",
          style: {
            width: 126,
            height: 112
          }
        }}
        emptyProps={{
          style: {
            paddingTop: 120
          }
        }}
        description="还没有关注任何用户哦"
      />
    )
  }
  return (
    <GpContainer className="min-h-screen">
      <View className={styles.list}>
        {state.list.length > 0
          ? state.list.map(l => (
              <View
                className={clsx(styles.item, {
                  [styles.isTop]: l.isTop
                })}
                key={l.followingMiniVisitorId}
              >
                <Image
                  onClick={() =>
                    navigation(pageMapperCommunity.PersonalPage, {
                      id: l.followingMiniVisitorId
                    })
                  }
                  src={l.followingMiniVisitorHead || process.env.__DEF_AVATAR__}
                  className={styles.image}
                />
                <View
                  className={styles.info}
                  onClick={() =>
                    navigation(pageMapperCommunity.PersonalPage, {
                      id: l.followingMiniVisitorId
                    })
                  }
                >
                  <View className={styles.name}>{l.followingMiniVisitorName}</View>
                  <View className={styles.desc}>{l.followingMiniVisitorDescription}</View>
                </View>
                <View className={styles.concernBtn} onClick={() => handleConcern(l)}>
                  {l.isMutual ? "互相关注" : "已关注"}
                </View>
              </View>
            ))
          : renderEmpty()}
      </View>
      <GpActionSheet
        open={state.openAction}
        closeFn={closeAction}
        actions={state.actions}
        onSelect={handleActionSelect}
      />
    </GpContainer>
  )
}
export default MyConcern
